{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import ee\n",
    "ee.Initialize()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "from ipygee import *"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Create a Map instance\n",
    "- Arguments:\n",
    "  - tabs: a `tuple` indicating which tabs to load in the map. Options are: Inspector, Layers, Assets, Tasks\n",
    "  - kwargs: as this class inherits from `ipyleaflet.Map` it can accept all its arguments"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "Map = Map()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Show map with method `show`\n",
    "- Arguments\n",
    "  - tabs: show tabs (bool)\n",
    "  - layer_control: show a control for layers (bool)\n",
    "  - draw_control: show a control for drawings (bool)\n",
    "  - fullscrean: show fullscreen button (bool)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "scrolled": false
   },
   "outputs": [
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "b4bdceb806ff4ac68c46282d41bcc70f",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Map(basemap={'url': 'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', 'attribution': 'Map data (c) <a href…"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "90aa05d87d404cff943753bc8cff6fc6",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Tab(children=(CustomInspector(children=(SelectMultiple(options=OrderedDict(), value=()), Accordion(selected_in…"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "Map.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Resize Map\n",
    "Dimensions must be in pixel units"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "Map.setDimensions('70%', '500px')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Load some Earth Engine Objects"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "site = ee.Geometry.Point([-72, -42])\n",
    "bounds = site.buffer(10000)\n",
    "\n",
    "collection = ee.ImageCollection('COPERNICUS/S2').filterBounds(bounds).filterDate('2019-01-01', '2019-02-01')\n",
    "image = collection.first()\n",
    "\n",
    "countries = ee.FeatureCollection('USDOS/LSIB_SIMPLE/2017')\n",
    "sa = countries.filterMetadata('wld_rgn', 'equals', 'South America')\n",
    "arg = ee.Feature(countries.filterMetadata('country_na', 'equals', 'Argentina').first())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Define visualization parameters"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [],
   "source": [
    "visParam = {'bands':['B8', 'B11', 'B4'], 'min':0, 'max':5000}"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Add Layers"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [],
   "source": [
    "Map.addLayer(site, name='site point')\n",
    "Map.addLayer(bounds, name='site bounds')\n",
    "Map.addLayer(image, visParam, name='Sentinel 2 Image')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Add all images from a collection"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [],
   "source": [
    "Map.addImageCollection(collection.limit(5), visParam, \n",
    "                       namePattern='S2 {system_date} clouds: {CLOUD_COVERAGE_ASSESSMENT}%')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Add FeatureCollection and Feature\n",
    "- visualization parameters:\n",
    "  - outline_color: color for the outline\n",
    "  - outline:  width of the outline\n",
    "  - fill_color: color for the inside"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [],
   "source": [
    "Map.addLayer(sa, {'outline_color':'red'}, name='South America')\n",
    "Map.addLayer(arg, {'fill_color':'blue', 'outline': 1}, name='Argentina')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Center object"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [],
   "source": [
    "Map.centerObject(bounds)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Get attributes"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "11"
      ]
     },
     "execution_count": 12,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# Zoom\n",
    "Map.zoom"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "((-65.6582745198266, -118.12500000000001),\n",
       " (65.65827451982663, 118.12500000000001))"
      ]
     },
     "execution_count": 13,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# ipyleaflet bounds (not Earth Engine)\n",
    "Map.bounds"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'coordinates': [[[-118.12500000000001, -65.6582745198266],\n",
       "   [-118.12500000000001, 65.65827451982663],\n",
       "   [118.12500000000001, 65.65827451982663],\n",
       "   [118.12500000000001, -65.6582745198266],\n",
       "   [-118.12500000000001, -65.6582745198266]]],\n",
       " 'type': 'Polygon'}"
      ]
     },
     "execution_count": 14,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# Earth Engine Bounds\n",
    "Map.getBounds().getInfo()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[-42.00000308012648, -71.9998286857986]"
      ]
     },
     "execution_count": 15,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# ipyleaflet center (not Earth Engine)\n",
    "Map.center"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'coordinates': [-71.9998286857986, -42.00000308012648], 'type': 'Point'}"
      ]
     },
     "execution_count": 16,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# Earth Engine Center\n",
    "Map.getCenter().getInfo()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Layers\n",
    "All Layers are contained in an `OrderedDict` where keys are the name of the layers and the value is a `dict` with the following keys:\n",
    "- layer: `ipyleaflet.TileLayer` added to the Map\n",
    "- object: Earth Engine Object used to create the Layer\n",
    "- type: type of EE Object\n",
    "- visParams: visualization parametes\n",
    "\n",
    "All layers can be accesed with `Map.EELayers`"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Get one layer by its name"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [],
   "source": [
    "layer = Map.getLayer('Sentinel 2 Image')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'layer': TileLayer(attribution='Map Data &copy; <a href=\"https://earthengine.google.com/\">Google Earth Engine</a> ', name='Sentinel 2 Image', options=['min_zoom', 'detect_retina', 'attribution', 'max_zoom', 'tile_size'], url='https://earthengine.googleapis.com/map/12d55689141a1230e95c5f1668144339/{z}/{x}/{y}?token=af553ad8bdd65700c3d7bd80297a96b7'),\n",
       " 'object': <ee.image.Image at 0x7fbfb814ec88>,\n",
       " 'type': 'Image',\n",
       " 'visParams': {'bands': 'B8,B11,B4', 'max': 5000, 'min': 0}}"
      ]
     },
     "execution_count": 18,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "layer"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Directly get the asociated EE object"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {},
   "outputs": [],
   "source": [
    "eelayer = Map.getObject('Sentinel 2 Image')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['B1',\n",
       " 'B2',\n",
       " 'B3',\n",
       " 'B4',\n",
       " 'B5',\n",
       " 'B6',\n",
       " 'B7',\n",
       " 'B8',\n",
       " 'B8A',\n",
       " 'B9',\n",
       " 'B10',\n",
       " 'B11',\n",
       " 'B12',\n",
       " 'QA10',\n",
       " 'QA20',\n",
       " 'QA60']"
      ]
     },
     "execution_count": 20,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "eelayer.bandNames().getInfo()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# TABS\n",
    "## You can add a custom Tab with a custom handler. The handler is a function with 4 main parameters:\n",
    "- **type:** the interaction type. Can be 'click', 'mouseover', etc\n",
    "- **coordinates:** the coordinates where the interaction has taken place. If you have used ipyleaflet before, take in consideraton that coordinates are inverted (to match GEE format): [longitud, latitude]\n",
    "- **widget:** The widget inside the Tab. Defaults to an empty HTML widget\n",
    "- **map:** the Map instance. You can apply any of its methods, or get any of its properties"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      " Add a Tab to the Panel. The handler is for the Map\n",
      "\n",
      "        :param name: name for the new tab\n",
      "        :type name: str\n",
      "        :param handler: handle function for the new tab. Arguments of the\n",
      "        function are:\n",
      "\n",
      "          - type: the type of the event (click, mouseover, etc..)\n",
      "          - coordinates: coordinates where the event occurred [lon, lat]\n",
      "          - widget: the widget inside the Tab\n",
      "          - map: the Map instance\n",
      "\n",
      "        :param widget: widget inside the Tab. Defaults to HTML('')\n",
      "        :type widget: ipywidgets.Widget\n",
      "        \n"
     ]
    }
   ],
   "source": [
    "print(Map.addTab.__doc__)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Check out the Map!\n"
     ]
    }
   ],
   "source": [
    "def test_handler(**change):    \n",
    "    # PARAMS\n",
    "    ty = change['type']\n",
    "    coords = change['coordinates']\n",
    "    wid = change['widget']\n",
    "    themap = change['map']\n",
    "        \n",
    "    if ty == 'click':  # If interaction was a click\n",
    "        # Loading message before sending a request to EE\n",
    "        wid.value = 'Loading...'\n",
    "        # Map's bounds\n",
    "        bounds = themap.getBounds().getInfo()['coordinates']\n",
    "        # Change Widget Value\n",
    "        wid.value = \"You have clicked on {} and map's bounds are {}\".format(coords, bounds)        \n",
    "\n",
    "Map.addTab('TestTAB', test_handler)\n",
    "print(\"Check out the Map!\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.5.2"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
